<?php
/**
 * Service_Exchange
 *
 * Класс Service_Exchange осуществляет работу с валютами
 *
 * @author Egorov Aleksandr (slamer86@gmail.com)
 */
class Service_Exchange {
	
	protected $arrRates = array(); // Массив с обменными курсами
	protected static $currency = 'RUB';
	protected static $changed = false;
	protected static $objExchange;
	
	/**
	 * Создание объекта. Если передана валюта, то курсы пересчитываются относительно нее
	 * 
	 * @param string $currency - валюта
	 */
	public function __construct() {
		Service_Debug::setDebug();
	  $this->setRates(self::$currency);
	}
	
	public static function setCurrency($currency) {
		Service_Debug::setDebug();
		if ($currency != self::$currency) self::$changed = true;
		self::$currency = $currency;
		
	}
	
	public static function getCurrency() {
		Service_Debug::setDebug();
		return self::$currency;
	}	
	
	public static function getManCurrency() {
		Service_Debug::setDebug();
		return '<span class="currency-symbol" data-currency="'.self::$currency.'"></span>';
	}	
	
	
	/**
	 * Получает курс валют относительно одной из них
	 * 
	 * @param string $currency - Трехзначный код валюты относительно которой получать курсы
	 */
	public static function getExchange($currency = 'RUB') {
		Service_Debug::setDebug();
		$objCurl = new Service_Curl();
	  // Старая версия
	  //$arrResult = $objCurl->httpRequest('GET', 'http://themoneyconverter.com/' . $currency . '/rss.xml');
	  $arrResult = $objCurl->httpRequest('GET', 'http://' . $currency . '.fxexchangerate.com/rss.xml');
	  return $arrResult;
	}
	
	/**
	 * Парсит курс валют относительно одной из них
	 * 
	 * @param string $currency - Трехзначный код валюты относительно которой получать курсы
	 */
	public static function parseExchange($currency = 'RUB') {
		Service_Debug::setDebug();
		$arrResult = self::getExchange($currency);
		if (isset($arrResult['channel']['item'])) {
			$objDB = Service_Database::instance();
			$i = 0;
			$arrCurrencies = array();
			foreach ($arrResult['channel']['item'] as $arrCurrencyData) {
				$arrCurrencies[$i]['currency_code'] = substr($arrCurrencyData['title'], strlen($arrCurrencyData['title']) - 4, 3);
				preg_match('|([\d]+) [\w ]+ = ([0-9\.]+)|', $arrCurrencyData['description'], $arrExchange);
				$arrCurrencies[$i]['exchange'] = $arrExchange[2] / $arrExchange[1];
				$stmt = "INSERT INTO currency_exchange (currency_code, exchange, updated_at) 
								 VALUES ('" . $arrCurrencies[$i]['currency_code'] . "', '" . $arrCurrencies[$i]['exchange'] . "', '" . Service_Date::gLocalTime2BD() . "')
								 ON DUPLICATE KEY 
								 UPDATE exchange = VALUES(exchange),
								 updated_at = VALUES(updated_at)
								 ";
				$objDB->query($stmt);
				$i++;
			}
		}
	}	
	
	/**
	 * Парсит курс валют 
	 * 
	 */
	public static function parseCbrExchange() {
		Service_Debug::setDebug();
		$objCurl = new Service_Curl();
	  $arrResult = $objCurl->httpRequest('GET', 'http://www.cbr.ru/scripts/XML_daily.asp');		
	  
		if (isset($arrResult['Valute'])) {
			$objDB = Service_Database::instance();
			$i = 0;
			$arrCurrencies = array();
			foreach ($arrResult['Valute'] as $arrCurrencyData) {
				$arrCurrencies[$i]['currency_code'] = $arrCurrencyData['CharCode'];
				$arrCurrencies[$i]['exchange'] = $arrCurrencyData['Nominal'] / floatval($arrCurrencyData['Value']);
				$stmt = "INSERT INTO currency_exchange (currency_code, exchange, updated_at) 
								 VALUES ('" . $arrCurrencies[$i]['currency_code'] . "', '" . $arrCurrencies[$i]['exchange'] . "', '" . Service_Date::gLocalTime2BD() . "')
								 ON DUPLICATE KEY 
								 UPDATE exchange = VALUES(exchange),
								 updated_at = VALUES(updated_at)
								 ";
				$objDB->query($stmt);
				$i++;
			}
		}
	}	
	
	/**
	 * Заполняем массив обменных курсов относительно валюты
	 */
	private function setRates() {
		Service_Debug::setDebug();
		$objDB = Service_Database::instance();
		$stmt = "SELECT * FROM currency_exchange";
		$this->arrRates = $objDB->select($stmt);
		$this->arrRates = Service_ArrayConverter::makeKeyArrayFromMultyArray($this->arrRates, 'currency_code');
		if (self::$currency != 'RUB') {
			$currencyRate = $this->arrRates[self::$currency]['exchange'];
			foreach ($this->arrRates as $currencyCode => $rate) {
				$this->arrRates[$currencyCode]['exchange'] = $rate['exchange'] / $currencyRate;
			}
			$this->arrRates['RUB']['exchange'] = 1 / $currencyRate; 
		}
	}
	
	public function getPrice($price, $currency, $round = 2) {
		Service_Debug::setDebug();
		if (isset($this->arrRates[$currency]['exchange'])) {
			if ($this->arrRates['RUB']['exchange'] < 10) $round = 0;
			
			$price = round($price / $this->arrRates[$currency]['exchange'], $round);
			$price = number_format($price, $round, ',', ' ');
			if (self::$currency == 'USD') $price = $price . '$';
			elseif (self::$currency == 'EUR') $price .= '&euro;';
			elseif (self::$currency == 'RUB') $price .= '&nbsp;' . Service_Translate::getText('руб.');
			else $price .= ' ' . self::$currency;
		}
		else {
			$price = round($price, $round);
			$price .= ' ' . $currency;
		}
		return $price;
	}
	
	public function getShortPrice($price, $currency, $round = 2) {
		Service_Debug::setDebug();
		if (isset($this->arrRates[$currency]['exchange'])) {
			if ($this->arrRates['RUB']['exchange'] < 10) $round = 0;
			$price = round($price / $this->arrRates[$currency]['exchange'], $round);
		}
		else $price = round($price, $round);
		return $price;
	}
	
	/**
	 * Возвращает span с заполненными аттрибутами для автоматической смены валюты
	 * 
	 * @param float $price - Цена
	 * @param string $currency - 3-х буквенный код валюты (RUB)
	 * @param int $round - Символов после запятой
	 */
	public function getSpanPrice($price, $currency, $round = 2) {
		Service_Debug::setDebug();
		if (isset($this->arrRates[$currency]['exchange'])) {
			if ($this->arrRates['RUB']['exchange'] < 10) $round = 0;
			$newPrice = round($price / $this->arrRates[$currency]['exchange'], $round);
		}
		else $newPrice = round($price, $round);
		return '<span data-price="' . $price . '" data-currency="' . $currency . '">' . $newPrice . '</span>';
	}

	
  /**
   * Функция обеспечивает работу шаблона Singleton.
   * Благодаря ей у нас всегда будет только один запрос на выборку курсов из БД
   *
   * @return resource
   */
  static public function instance() {
  	//Service_Debug::setDebug();
    if (!isset(self::$objExchange) || self::$changed) {
      self::$objExchange = new Service_Exchange();
    }
    return self::$objExchange;
  }

  /**
   * Возвращает курсы валют относительно текущей
   * 
   * @return array - массив курсов валют
   */
  public function getRates() {
  	Service_Debug::setDebug();
  	return Service_ArrayConverter::makeKeySimpleArrayFromMultyArray($this->arrRates, 'currency_code', 'exchange');
  }

	
}
?>